<?php
require 'protected/vendor/autoload.php';
use Elasticsearch\ClientBuilder;
/*
 * Note:elasticsearch服务层.
 * Author:04007
 */ 
class ES{
    public $server, $index, $url, $pagesize;
    public $client;
    //初始化一些配置及参数
    public function __construct($config)
    {
        
        try{
            //构建客户端对象
            $this->client = ClientBuilder::create()->setHosts($config['search_host'].":".$config['search_port'])->build();
        }catch (\Exception $e){
            throw $e;
            
        }
    }
    /**
     * 创建一个索引
     * @author joniding
     * @param $index
     * @param $settings
     * @return array
     * @throws \Exception
     */
    public function createIndex($index,$settings = array())
    {
        try{
            $initParams['index'] = $index;
            !empty($settings) && $initParams['body']['settings'] = $settings;
            $res = $this->client->indices()->create($initParams);
        }catch(\Exception $e){
            throw $e;
        }
        return $res;
    }
    /**
     * 删除索引
     * @param  $index
     */
    public function deleteIndex($index){
        try{
            $params['index'] = $index;
            $res = $this->client->delete($params);
        }catch (\Exception $e){
            throw $e;
        }
        if (!isset($res['_shards']['successful'])){
            return false;
        }
        return true;
    }
    /**
     * 根据唯一id删除
     * @author joniding
     * @param  $index
     * @param $id
     * @return bool
     * @throws \Exception
     */
    public function delete($index,$id)
    {
        try{
            $params['index'] = $index;
            $params['id'] = $id;
            $res = $this->client->delete($params);
        }catch (\Exception $e){
            throw $e;
        }
        if (!isset($res['_shards']['successful'])){
            return false;
        }
        return true;
    }
    /**
     * 更新索引的映射 mapping
     * @author joniding
     * @param $data
     * @return array
     * @throws \Exception
     */
    public function setMapping($index,$data)
    {
        try{
            $initParams['index'] = $index;
            $initParams['body'] = $data;
            $res = $this->client->indices()->putMapping($initParams);
        }catch (\Exception $e){
            throw $e;
        }
        return $res;
    }

}
?>